package com.steakliu.sun.ratelimiter;

import com.steakliu.sun.ratelimiter.api.AbstractRateLimiter;
import com.steakliu.sun.spi.annotation.Join;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 功能说明： 原生限流
 * <p>
 * Original @Author: steakliu-刘牌, 2023-02-07  20:59
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
@Join
public class NativeRateLimiter extends AbstractRateLimiter {
    private final Logger LOGGER = LoggerFactory.getLogger(NativeRateLimiter.class);

    private final AtomicInteger counter = new AtomicInteger(0);
    private volatile long lastTimeStamp = System.currentTimeMillis();
    private final ThreadLocal<Boolean> threadLocal = new ThreadLocal<>();

    @Override
    public boolean tryAcquire() {
        long currentTimeStamp = System.currentTimeMillis();
        LOGGER.info("时间间隔：  " + (currentTimeStamp - lastTimeStamp));
        if (currentTimeStamp - lastTimeStamp >= milliseconds) {
            lastTimeStamp = currentTimeStamp;
            counter.set(0);
            return true;
        }
        if (counter.incrementAndGet() <= permits) {
            threadLocal.set(true);
            return true;
        }
        return false;
    }

    @Override
    public void release() {
        if (threadLocal.get()) {
            try {
                counter.decrementAndGet();
            } finally {
                threadLocal.remove();
            }
        }
    }
}
